package com.dhcc.android.base.utils;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.dhcc.android.base.R;
import com.dhcc.android.base.base.MSApplication;
import com.dhcc.android.base.common.bean.BasicProperties;
import com.dhcc.android.base.common.bean.Item;
import com.dhcc.android.base.common.bean.KeyValueBean;
import com.dhcc.android.base.common.bean.Node;
import com.dhcc.android.base.common.bean.Task;
import com.dhcc.android.base.common.view.AutoCompleteTextView.MyAutoCompleteTextView;
import com.dhcc.android.base.db.DBImportUtil;
import com.dhcc.android.base.gis.DataController;
import com.dhcc.android.base.gis.FactoryGPS;
import com.dhcc.android.base.gis.SelectItemChangedListener;
import com.dhcc.android.base.gis.TouchLongTool;
import com.dhcc.android.base.utils.dataparse.DataParse;
import com.dhcc.android.base.utils.dataparse.NodeParse;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import srs.DataSource.DataTable.DataColumnCollection;
import srs.DataSource.DataTable.DataRowCollection;
import srs.DataSource.DataTable.DataTable;
import srs.DataSource.Vector.IFeatureClass;
import srs.DataSource.Vector.ShapeFileClass;
import srs.Display.Symbol.ISimpleFillSymbol;
import srs.Display.Symbol.SimpleFillStyle;
import srs.Display.Symbol.SimpleFillSymbol;
import srs.Display.Symbol.SimpleLineStyle;
import srs.Display.Symbol.SimpleLineSymbol;
import srs.Element.FillElement;
import srs.Element.IFillElement;
import srs.Element.IPicElement;
import srs.GPS.GPSControl;
import srs.GPS.GPSConvert;
import srs.Geometry.Envelope;
import srs.Geometry.IEnvelope;
import srs.Geometry.IGeometry;
import srs.Geometry.IPoint;
import srs.Geometry.IPolygon;
import srs.Geometry.Point;
import srs.Layer.CommonLayer;
import srs.Layer.FeatureLayer;
import srs.Layer.IFeatureLayer;
import srs.Layer.ILayer;
import srs.Map.IMap;
import srs.Map.Map;
import srs.Utility.sRSException;
import srs.tools.MapControl;
import srs.tools.ZoomInCommand;
import srs.tools.ZoomOutCommand;

/**
 * 除字符公共以外的共用数据处理
 *
 * @author pengling
 * @date 2014-9-3
 */
public class CommenUtil {
    private static TextView tv_info = null;
    private static MapControl mMapControl = null;
    private static IMap mMap = null;


    public static void getYFMapBitmap() {
        Constants.ZRDKBITMAP = mMap.ExportMap(false);
    }


    public static TextView getGPSInfo(Context context) {

        if (tv_info != null) {
            return tv_info;
        } else if (context != null) {
            return new TextView(context);
        }
        return tv_info;
    }

    private static TouchLongTool mTouchLongTool = null;
    /**
     * 是否为列表选中的 add lizhongyi 20150620
     */
    public static boolean IsListSelected = true;

    /**
     * CommonLayer
     */
    public static CommonLayer cl = new CommonLayer();

    /**
     * 选中对象高亮显示样式
     */
    public static ISimpleFillSymbol FSYMBOL = new SimpleFillSymbol(Color.argb(
            16, 0, 255, 255), new SimpleLineSymbol(Color.rgb(0, 255, 255), 4,
            SimpleLineStyle.Solid), SimpleFillStyle.Soild);

    public static Bitmap BitmapTarget = null;

    /**
     * 获取任务总样本数
     */
    public static int getCount(String root, String taskTitle) {
        List<Node> list = getNodeList(root, taskTitle);

        Node n = list.get(list.size() - 1);

        DBImportUtil.openDatabase(root, taskTitle, "/TASK/DATA.db");
        return DBImportUtil.count(n.getTable());
    }

    /**
     * 获取任务已调查样本数
     */
    public static int getResearchNum(String root, String taskTitle) {
        String path = root + "/" + taskTitle + "/SURVEY";
        List<File> list = getResearchList(path);

        return list.size();
    }

    public static String formatterZero(int num) {
        String str = "";
        if (num >= 10) {
            str = num + "";
        } else {
            str = "0" + num;
        }
        return str;
    }


    /**
     * 面积保留 n 位小数
     */
    public static String formatterMJ(double area, String pattern) {
        DecimalFormat df = new DecimalFormat(pattern);
        return df.format(area);
    }

    /**
     * 面积保留4位小数
     */
    public static String formatterMJ(double area) {
        DecimalFormat df = new DecimalFormat("######0.0000");
        return df.format(area);
    }

    /**
     * 亩 转换成 平方米
     */
    public static String MUtoPFM(String mu) {
        if (StringUtil.isNotEmpty(mu)) {
            double d = Double.valueOf(mu);
            d = d * 666.7;
            DecimalFormat df = new DecimalFormat("######0.0000");
            return df.format(d);
        }
        return "";
    }

    /**
     * 平方米 转换成 亩
     */
    public static String PFMtoMU(String pfm) {
        if (StringUtil.isNotEmpty(pfm)) {
            double d = Double.valueOf(pfm);
            d = d / 666.7;
            DecimalFormat df = new DecimalFormat("######0.0000");
            return df.format(d);
        }
        return "";
    }


    /**
     * 获取新增地块 DKBHU
     *
     * @param yfbhu
     * @param lastYFDKBH
     */
    public static String getNewDKBHU(String lastYFDKBH) {
        if (lastYFDKBH.indexOf("-") != -1) {
            lastYFDKBH = lastYFDKBH.substring(0, lastYFDKBH.indexOf("-"));
        }
        long a = Long.valueOf(lastYFDKBH) + 1;
        return String.valueOf(a);
    }

    /**
     * 获取分割地块 DKBHU
     *
     * @param dkbhu
     * @param i
     */
    public static String getShearDKBHU(String dkbhu, int big, int i) {
        String n = "";
        if (dkbhu.contains("-")) {
            dkbhu = dkbhu.substring(0, dkbhu.indexOf("-"));
            n = formatterZero(big + i);
        } else {
            n = formatterZero(i);
        }

        return dkbhu + "-" + n;
    }

    /**
     * 获取分割地块 YFDKBH
     *
     * @param YFDKBH
     * @param i
     */
    public static String getShearYFDKBH(String YFDKBH, int i) {
        return YFDKBH + "-" + i;
    }

    /**
     * 更改设置
     */
    public static void changeSettings(String key, String value) {

        if (MSApplication.GPS_REFRESH_TIME.equals(key)) {// gps刷新时间
            FactoryGPS.TIME_REFRESH = Integer.parseInt(value);
        } else if (MSApplication.NOTE_DISTANCE.equals(key)) {// 提示距离

        } else if (MSApplication.CATCH_RANGE.equals(key)) {// 捕捉距离
            TouchLongTool.Dis = Float.parseFloat(value);
        }
    }


    /**
     * 给AutoText框设置公共样式
     *
     * @param textView
     * @param hint
     * @param inputType
     * @param imeOptions
     * @param leftDrawable
     */
    public static void setAutoTextStyle(MyAutoCompleteTextView textView,
                                        String hint, int inputType, int imeOptions, int leftDrawable) {
        LayoutParams layoutParam = new LayoutParams(
                LayoutParams.FILL_PARENT,
                Constants.screenHight / 12);
        textView.setLayoutParams(layoutParam);
        textView.setText("");
        textView.setClearIconVisible(false);
        textView.setPaddings(22, 0, 12, 0);
        textView.setDefaultHint(hint);
        textView.setbackgroundImg(R.drawable.border_gray_t1_b1);
        textView.setLeftDrawable(leftDrawable, 10);
        textView.setRightDrawable(R.mipmap.input_clear);
        textView.setHintTextColor(0xffbec3c6);
        textView.setTextColor(0xff5a6378);
        textView.setTextSize(14);
        if (inputType != -1) {
            textView.setInputType(inputType);
        }
        textView.setImeOptions(imeOptions);
    }


    /**
     * 获取选择列表 对应保存数据库表中的 字段
     */
    public static KeyValueBean getSelectListKeyValue(List<BasicProperties> fieldList, String key, String value) {
        KeyValueBean kvb = new KeyValueBean();
        for (BasicProperties bp : fieldList) {
            if (bp.getInput().startsWith("5") || bp.getInput().contains("|5")) {
                if (bp.getPfeild().equals(key)) {
                    kvb.setKey(bp.getName());
                } else if (bp.getPfeild().equals(value)) {
                    kvb.setValue(bp.getName());
                    kvb.setFieldset(bp.getInput());
                }
            }
        }
        return kvb;
    }

    /**
     * 获取选择列表 对应保存数据库表中的 字段
     */
    public static KeyValueBean getSelectListKey(List<BasicProperties> fieldList){
        KeyValueBean kvb = new KeyValueBean();
        for(BasicProperties bp : fieldList){
            if(bp.getInput().startsWith("5") || bp.getInput().contains("|5")){
                kvb.setKey(bp.getName());
                kvb.setFieldset(bp.getInput());
            }
        }
        return kvb;
    }


    /**
     * 获取调查期对应的地块表名
     *
     * @param table
     * @param period
     */
    public static String getTableName(String table, String period) {
        String name = table;
        if (period.contains("春播") || period.contains("早稻面积")) {
            name += "C";
        } else if (period.contains("夏播")) {
            name += "X";
        } else if (period.contains("秋冬播")) {
            name += "QD";
        }

        return name;
    }

    /**
     * 获取调查期缩写
     */
    public static String getDCQ(String period) {
        String name = "";
        if (period.contains("春播") || period.contains("早稻面积")) {
            name = "C";
        } else if (period.contains("夏播")) {
            name = "X";
        } else if (period.contains("秋冬播")) {
            name = "QD";
        }
        return name;
    }

    /**
     * 生成UUID
     */
    public static String createUUID() {
        return UUID.randomUUID().toString().replace("-", "");
    }


    /**
     * 前台显示
     *
     * @param text
     * @param activity
     */
    public static void toast(String text, Context context) {
        Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
    }

    /**
     * 获取配置文件流
     *
     * @param add
     * @return
     */
    public static InputStream initStreamData(String properties, String path,
                                             Context context) {
        InputStream input = null;
        if (StringUtil.isNotEmpty(properties)) {
            try {
                input = new BufferedInputStream(new FileInputStream(path
                        + properties));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        } else {
            CommenUtil.toast("找不到文件！", context);
        }
        return input;
    }

    public static String createUUID(String sign) {
        if (sign == null) {
            sign = "";
        }
        String s = sign + UUID.randomUUID().toString();

        return s;
    }

    /**
     * 获取选择列表 值 对应的字段名
     */
    public static String getSelectLabelField(List<BasicProperties> fieldList) {
        String f = "";
        for (BasicProperties bp : fieldList) {
            if (bp.getInput().startsWith("5") || bp.getInput().contains("|5")) {
                f = bp.getName();
            }
        }
        return f;
    }

    /**
     * 获取选择列表 值 对应的字段名
     */
    public static List<KeyValueBean> getJCField(List<BasicProperties> fieldList) {
        List<KeyValueBean> list = new ArrayList<KeyValueBean>();
        for (BasicProperties bp : fieldList) {
            if (StringUtil.isNotEmpty(bp.getInherit())) {
                if (bp.getInherit().equals("1")) {
                    KeyValueBean kv = new KeyValueBean();
                    kv.setKey(bp.getName());
                    kv.setValue(bp.getPfeild());
                    kv.setType(1);

                    list.add(kv);
                } else if (bp.getInherit().equals("2")) {
                    KeyValueBean kv = new KeyValueBean();
                    kv.setKey(bp.getName());
                    kv.setValue(bp.getPfeild());
                    kv.setType(2);

                    list.add(kv);
                }
            }
        }
        return list;
    }

    /**
     * 将item转为KeyValue
     *
     * @param itemList
     * @param isShowKey
     * @return
     */
    public static List<KeyValueBean> itemToKeyValue(List<Item> itemList,
                                                    int showType) {
        List<KeyValueBean> kvList = new ArrayList<KeyValueBean>();
        for (Item item : itemList) {
            KeyValueBean kv = new KeyValueBean();
            switch (showType) {
                case 1:// 如：103
                    kv.setValue(item.getFeild());
                    break;
                case 2:// 如：水稻
                    kv.setValue(item.getLabel());
                    break;
                case 3:// 如：水稻（103）
                    kv.setValue(item.getLabel() + "(" + item.getFeild() + ")");
                    break;
                default:
                    break;
            }
            kv.setFieldset(item.getFieldset());
            kv.setKey(item.getFeild());
            kvList.add(kv);
        }
        return kvList;

    }

    /**
     * 根据属性名获取属性值
     */
    public static Object getFieldValueByName(String fieldName, Object obj) {
        Object value = "";
        if (fieldName.matches(".*[A-Z].*")) {// 含有大写,全部转成小写
            fieldName = fieldName.toLowerCase();
        }
        try {
            String fr = fieldName.substring(0, 1).toUpperCase();
            String getter = "get" + fr + fieldName.substring(1);
            Method m = obj.getClass().getDeclaredMethod(getter, new Class[0]);
            value = m.invoke(obj, new Object[]{});

        } catch (Exception e) {
            e.printStackTrace();
        }

        return value;
    }

    /**
     * 将item转为String集合
     *
     * @param itemList
     * @return
     */
    public static List<String> itemToStrList(List<Item> itemList) {
        List<String> strList = new ArrayList<String>();
        for (Item item : itemList) {
            strList.add(item.getFeild());
        }
        return strList;

    }

    /**
     * 将item转为String集合
     *
     * @param itemList
     * @return
     */
    public static List<String> basicPropertieToStrList(
            List<BasicProperties> bpList) {
        List<String> strList = new ArrayList<String>();
        for (BasicProperties bp : bpList) {
            strList.add(bp.getName());
        }
        return strList;

    }

    /**
     * 将item转为String集合
     *
     * @param itemList
     * @return
     */
    public static List<String> basicPropertieToStrList(
            List<BasicProperties> bpList, String key) {
        List<String> strList = new ArrayList<String>();
        for (BasicProperties bp : bpList) {
            strList.add(bp.getName());
        }
        strList.add(key);
        return strList;

    }

    /**
     * 解析任务列表
     *
     * @param period 对应的调查期
     */
    public static List<Task> listTask(String root) {
        System.out.println("###--解析所有已下载的任务");
        // 解析任务
        List<Task> taskList = new ArrayList<Task>();
        // String root = Environment.getExternalStorageDirectory() + "/test";
        File file = new File(root);
        File[] files = file.listFiles();

        if (files != null) {
            for (File f : files) {
                if (f.isDirectory()) {
                    File[] cfs = f.listFiles();
                    for (File ff : cfs) {
                        System.out.println("文件名：" + ff.getName());
                        if (ff.isFile() && ff.getName().equals("CONFIG.xml")) {
                            try {
                                InputStream inp = new FileInputStream(ff);
                                Task task = DataParse.parseTask(inp);

                                if (task != null) {
                                    taskList.add(task);
                                }
                            } catch (FileNotFoundException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        }

        return taskList;
    }

    /**
     * 解析任务列表
     *
     * @param period 对应的调查期
     */
    public static List<Task> listTask(String root, String period) {
        System.out.println("###--条件：" + period);
        // 解析任务
        List<Task> taskList = new ArrayList<Task>();
        // String root = Environment.getExternalStorageDirectory() + "/test";
        File file = new File(root);
        File[] files = file.listFiles();

        if (files != null) {
            for (File f : files) {
                if (f.isDirectory()) {
                    File[] cfs = f.listFiles();
                    for (File ff : cfs) {
                        System.out.println("文件名：" + ff.getName());
                        if (ff.isFile() && ff.getName().equals("CONFIG.xml")) {
                            try {
                                InputStream inp = new FileInputStream(ff);
                                Task task = DataParse.parseTask(inp, period);

                                if (task != null) {
                                    taskList.add(task);
                                }
                            } catch (FileNotFoundException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        }

        return taskList;
    }

    /**
     * 解析任务列表
     *
     * @param period 对应的调查期
     * @param table  对应的表
     */
    public static List<Task> listTask(String root, String period, String table) {
        System.out.println("###--条件1：" + period);
        System.out.println("###--条件2：" + table);
        // 解析任务
        List<Task> taskList = new ArrayList<Task>();
        // String root = Environment.getExternalStorageDirectory() + "/test";
        File file = new File(root);
        File[] files = file.listFiles();

        if (files != null) {
            for (File f : files) {
                if (f.isDirectory()) { //判断是否为文件夹
                    File[] cfs = f.listFiles();
                    for (File ff : cfs) {
                        System.out.println("文件名：" + ff.getName());
                        if (ff.isFile() && ff.getName().equals("CONFIG.xml")) {
                            try {
                                InputStream inp = new FileInputStream(ff);
                                Task task = DataParse.parseTask(inp, period,
                                        table);
                                if (task != null) {
                                    taskList.add(task);
                                }
                            } catch (FileNotFoundException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        }

        return taskList;
    }

    /**
     * 解析层级节点
     */
    public static List<Node> getNodeList(String root, String taskTitle) {
        List<Node> nodeList = new ArrayList<Node>();
        String p = root + "/" + taskTitle + "/TASK/TASK.xml";

        try {
            InputStream is = new FileInputStream(p);
            nodeList = NodeParse.parseNodeList(is);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        System.out.println("-----" + nodeList.size());
        return nodeList;
    }

    /**
     * 获取已经调查完的样本
     *
     * @param path 调查结果保存路径
     */
    public static List<File> getResearchList(String path) {
        List<File> list = new ArrayList<File>();

        File file = new File(path);
        File[] files = file.listFiles();

        if (files != null) {
            for (File f : files) {
                if (f.isDirectory()) {
                    list.add(f);
                }
            }

        }

        return list;
    }

    // ----------------------------地图--------------------------------------------

    /**
     * 获取特定点的经纬度坐标
     */
    public static String getLatLon() {
        GPSControl mGPSControl = GPSControl.getInstance();
        double latitude = 0.0;
        double longitude = 0.0;
        if (mGPSControl.GPSOpened()) {
            latitude = mGPSControl.GPSLatitude;
            longitude = mGPSControl.GPSLongitude;
        } else {
            System.out.println("GPS定位功能已关闭");
        }
        String latlon = String.valueOf(latitude) + ","
                + String.valueOf(longitude);
        System.out.println("GPS定位：" + latlon);
        return latlon;
    }

    /**
     * 获取地图
     *
     * @return
     */
    public static IMap getMap() {
        return mMap;
    }

    /**
     * 获取地图控件
     *
     * @return
     */
    public static MapControl getMapControl() {
        return mMapControl;
    }

    /**
     * 刷新地图
     */
    public static void Refresh() {
        if (mMapControl != null) {
            mMapControl.Refresh();
        }
    }

    /**
     * 缩放至选中： 正序用
     *
     * @param index   选中的对象
     * @param targetL 操作图层
     * @return 缓冲至的范围
     */
    public static IEnvelope setZoomto(int index, IFeatureLayer targetL) {
        if (targetL != null && index > -1
                && targetL.getFeatureClass().getFeatureCount() > index) {
            try {
                IEnvelope env = targetL.getFeatureClass().getGeometry(index)
                        .Extent();
                env = new Envelope(env.XMin() - env.Width() / 10, env.YMin()
                        - env.Height() / 10, env.XMax() + env.Width() / 10,
                        env.YMax() + env.Height() / 10);
                mMap.setExtent(env);
                return env;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 缩放至选中：逆序用 added by 李忠义 20150619
     *
     * @param env
     */
    public static void setZoomto(IEnvelope env) {
        mMap.setExtent(env);
    }

    /**
     * @param context
     * @param view
     */
    public static void configMap(Context context, LinearLayout view) {
        mMapControl = new MapControl(context);
        view.addView(mMapControl, LinearLayout.LayoutParams.FILL_PARENT,
                LinearLayout.LayoutParams.FILL_PARENT);
        // 向map中添加图层
        if (mMap == null && mMapControl.getActiveView().FocusMap() != null) {
            mMap = mMapControl.getActiveView().FocusMap();
            mMapControl.getActiveView().FocusMap(mMap);
        } else if (mMap != null) {
            mMapControl.getActiveView().FocusMap(mMap);
        } else {
            // 否则创建一个新的Map
            mMap = new Map(new Envelope(0, 0, mMapControl.getWidth(),
                    mMapControl.getHeight()));
            mMapControl.getActiveView().FocusMap(mMap);
        }

        // add 杨宗仁 定位，放大，缩小按钮
        LayoutParams sp_params1 = new LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        LayoutParams sp_params2 = new LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        LayoutParams sp_params3 = new LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        ImageView btnZoomin = new ImageView(context);
        ImageView btnZoomout = new ImageView(context);
        ImageView ivLocationCenter = new ImageView(context);
        btnZoomin.setImageResource(R.mipmap.zoom_in);
        btnZoomout.setImageResource(R.mipmap.zoom_out);
        ivLocationCenter.setImageResource(R.mipmap.gps_recieved);

        btnZoomin.setBackgroundResource(R.drawable.duidi_bt_clickerstyle2);
        btnZoomout.setBackgroundResource(R.drawable.duidi_bt_clickerstyle2);
        ivLocationCenter
                .setBackgroundResource(R.drawable.duidi_bt_clickerstyle2);

        sp_params1.width = Constants.screenWidth / 11;
        sp_params1.height = Constants.screenWidth / 11;
        sp_params1.bottomMargin = Constants.screenWidth / 11 + 32;
        sp_params1.rightMargin = 16;
        sp_params1.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        sp_params1.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);

        btnZoomin.setLayoutParams(sp_params1);

        sp_params2.width = Constants.screenWidth / 11;
        sp_params2.height = Constants.screenWidth / 11;
        sp_params2.rightMargin = 16;
        sp_params2.bottomMargin = 16;
        sp_params2.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        sp_params2.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        btnZoomout.setLayoutParams(sp_params2);

        sp_params3.width = Constants.screenWidth / 11;
        sp_params3.height = Constants.screenWidth / 11;
        sp_params3.leftMargin = 16;
        sp_params3.bottomMargin = 30;
        sp_params3.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        sp_params3.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
        ivLocationCenter.setLayoutParams(sp_params3);

        mMapControl.setGravity(Gravity.BOTTOM);

        mMapControl.addView(btnZoomin);
        mMapControl.addView(btnZoomout);
        mMapControl.addView(ivLocationCenter);
        if (btnZoomin != null) {
            btnZoomin.setOnTouchListener(new OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    switch (event.getAction()) {
                        case MotionEvent.ACTION_DOWN:
                            ZoomInCommand zoomin = new ZoomInCommand();
                            zoomin.setBuddyControl(mMapControl);
                            zoomin.setEnable(true);
                            zoomin.onClick(v);
                    }
                    return true;
                }
            });
        }
        if (btnZoomout != null) {
            btnZoomout.setOnTouchListener(new OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    switch (event.getAction()) {
                        case MotionEvent.ACTION_DOWN:
                            ZoomOutCommand zoomout = new ZoomOutCommand();
                            zoomout.setBuddyControl(mMapControl);
                            zoomout.setEnable(true);
                            zoomout.onClick(v);
                    }
                    return true;
                }
            });
        }

        if (ivLocationCenter != null) {
            ivLocationCenter.setOnTouchListener(new OnTouchListener() {
                @Override
                public boolean onTouch(View arg0, MotionEvent arg1) {
                    SetLocationCenter(mMapControl);
                    return true;
                }
            });
        }

    }

    /**
     * 设置当前位置屏幕局中
     * <p/>
     * add 杨宗仁
     */
    public static void SetLocationCenter(MapControl mapControl) {

        IEnvelope mapEnv = mapControl.getActiveView().FocusMap().getExtent();
        GPSControl gpsControl = GPSControl.getInstance();
        // 39.9572698255,116.3642899000
        double xy[] = GPSConvert.GEO2PROJECT(gpsControl.GPSLongitude,
                gpsControl.GPSLatitude, mMap.getGeoProjectType());
        IPoint centerPoint = new Point(xy[0], xy[1]);
        double width = mapEnv.XMax() - mapEnv.XMin();
        double height = mapEnv.YMax() - mapEnv.YMin();
        IEnvelope envelope = new Envelope(centerPoint.X() - width / 2,
                centerPoint.Y() - height / 2, centerPoint.X() + width / 2,
                centerPoint.Y() + height / 2);
        mapControl.getActiveView().FocusMap().setExtent(envelope);
        mapControl.Refresh();
    }

    /**
     * 高亮显示选中目标区域
     *
     * @param layer   图层
     * @param fid     选中顺序号
     * @param control 地图控件
     * @param point   选中点：1.在图选中为手指点击位置；2.在列表选中为目标位置中心点
     * @throws IOException
     */
    public static void setLightSelected(IFeatureLayer layer, int fid,
                                        MapControl control, IPoint targetPoint) throws IOException {
        control.getElementContainer().ClearElement();

		/* 选中区域高亮显示 */
        IGeometry geo = layer.getFeatureClass().getGeometry(fid);
        IFillElement selElement = new FillElement();
        selElement.setGeometry(geo);
        selElement.setSymbol(FSYMBOL);
        control.getElementContainer().AddElement(selElement);

		/* 添加选中目标点位 */
        IPicElement picElement = new srs.Element.PicElement();
        if (BitmapTarget == null) {
            BitmapTarget = BitmapFactory.decodeResource(control.getContext()
                    .getResources(), R.mipmap.target);
        }
        picElement.setPic(BitmapTarget, -BitmapTarget.getWidth() / 2,
                -BitmapTarget.getHeight());
        picElement.setGeometry(targetPoint);
        control.getElementContainer().AddElement(picElement);
    }


    /**
     * 高亮显示选中目标区域
     *
     * @param CommonLayer 图层
     * @param fid         选中顺序号
     * @param control     地图控件
     * @param point       选中点：1.在图选中为手指点击位置；2.在列表选中为目标位置中心点
     * @throws IOException
     */
    public static void setLightSelected(CommonLayer commonLayer, int fid,
                                        MapControl control, IPoint targetPoint) throws IOException {
        control.getElementContainer().ClearElement();

		/* 选中区域高亮显示 */
        IGeometry geo = commonLayer.getGeometry(fid);
        IFillElement selElement = new FillElement();
        selElement.setGeometry(geo);
        selElement.setSymbol(FSYMBOL);
        control.getElementContainer().AddElement(selElement);

		/* 添加选中目标点位 */
        IPicElement picElement = new srs.Element.PicElement();
        if (BitmapTarget == null) {
            BitmapTarget = BitmapFactory.decodeResource(control.getContext()
                    .getResources(), R.mipmap.target);
        }
        picElement.setPic(BitmapTarget, -BitmapTarget.getWidth() / 2,
                -BitmapTarget.getHeight());
        picElement.setGeometry(targetPoint);
        control.getElementContainer().AddElement(picElement);
    }

    /**
     *
     * @param context
     * @param view
     * @param path
     */
    /*public static ILayer loadMap(Context context, LinearLayout view,
            String path, List<Integer> indexsOfSelected,int level) {

		String mImagePath = path + "/IMAGE/RENDER.tcf";
		String mTaskPath = path + "/TASK/RENDER.tcf";
		// add 李忠义
		// 20150609
		// 当前操作图层
		ILayer targetLayer = null;

		configMap(context, view);

		DataController controller = DataController.getInstance();
		controller.loadDataController(mImagePath, mTaskPath);
		controller.setmMap(mMap);
		try {
			controller.AddImage();
			// 获取TASK/Render.tcf 中的TaskLayer 标签的name值，作为输入参数
			String taskLayerName = controller.getmTASK().GetTaskLayer(level).Name;
			targetLayer = controller.setActiveLayer(taskLayerName,
					indexsOfSelected , true );
			// 添加点选目标
//			StartTouchLong(controller.getLayer(taskLayerName), context, view);
			// 刷新地图上的全部图层
			mMapControl.Refresh();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return targetLayer;
	}
	*/

    /**
     * 加载GIS地图
     */
    public static ILayer loadMap(Context context, LinearLayout view,
                                 String path, List<Integer> indexsOfSelected, int type) {

        String mImagePath = path + "/IMAGE/RENDER.tcf";
        String mTaskPath = path + "/TASK/RENDER.tcf";
        // add 李忠义
        // 20150609
        // 当前操作图层
        ILayer targetLayer = null;

        configMap(context, view);

        DataController controller = DataController.getInstance();
        controller.loadDataController(mImagePath, mTaskPath);
        controller.setmMap(mMap);
        try {
            controller.AddImage();
            // 获取TASK/Render.tcf 中的TaskLayer 标签的name值，作为输入参数
            String taskLayerName = controller.getmTASK().GetTaskLayer(0).Name;
            targetLayer = controller.setActiveLayer(taskLayerName,
                    indexsOfSelected/* , true */);
            //设置地图范围是目标图层的范围
            IEnvelope env = targetLayer.getExtent();
            mMap.setExtent(env);
            // 添加点选目标
            StartTouchLong(controller.getLayer(taskLayerName), context, view, type);
            // 刷新地图上的全部图层
            mMapControl.Refresh();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return targetLayer;
    }

    /**
     * edit 李忠义 20150609 开启地图点击选择操作
     */
    public static void StartTouchLong(final IFeatureLayer targetL,
                                      final Context context, final View parent, final int type) {
        // targetL为操作图层，开发人员根据需要自行修改获取方式
        // IFeatureLayer targetL= MapShowControler.SURVEYLAYER;
        if (targetL != null) {
            mTouchLongTool = new TouchLongTool(targetL);
            if (true) {
                mMapControl.ClearDrawTool();
                mTouchLongTool.setBuddyControl(mMapControl);// mapControl为操作的地图控件
                mTouchLongTool.onClick(mMapControl);
                mTouchLongTool.setEnable(true);
                // 设置不累计选择项目
                mTouchLongTool.IsOnlyOneTime = false;
                // 设置是不为单选
                mTouchLongTool.IsOnlyOneSelect = false;
                // 设置选中或未选中条目时，触发的事件
                mTouchLongTool.zoom2Selected = new SelectItemChangedListener() {
                    @Override
                    public void doEventSettingsChanged(Object tar) {
                        // 选中或未选中目标时，界面与地图上的相关反应。开发人员根据实际情况调用相关函数
                        Integer index = (Integer) tar;
                        IsListSelected = false;

                        System.out.println("####地图点选的下一级位置：" + index);
//                        if (type == 1) {
//                            ((MapSelectActivity) context).itemSelected(index, true);
//                        } else if (type == 2) {
//                            ((YCMapSelectActivity) context).itemSelected(index, true);
//                        } else if (type == 3) {
//                            ((GCMapSelectActivity) context).itemSelected(index, true);
//                        } else if (type == 4) {
//                            ((SGSCMapSelectActivity) context).itemSelected(index, true);
//                        }
                    }
                };
                mMapControl.setDrawTool(mTouchLongTool);
            }
        }
    }

    /**
     * edit by pengling;开启GPS服务的方法
     *
     * @param activity
     * @param receiver
     */
    public static void startGPSService(Activity activity,
                                       BroadcastReceiver receiver) {

        // 注册广播
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constants.LOCATION_ACTION);
        activity.registerReceiver(receiver, filter);
        Constants.isRegistered = true;
        // 启动服务
        Intent intent = new Intent();
        intent.setClass(activity, LocationService.class);
        activity.startService(intent);
    }

    /**
     * add by pengling 对geometrys进行非空判断和赋值
     *
     * @return
     */
    public static IGeometry getGeo(int i) {
        IGeometry geometry = null;
        if (Constants.geometrys.size() > 0) {
            geometry = Constants.geometrys.get(i);
        } else {
            geometry = Constants.geometry;
        }
        return geometry;
    }


    /**
     * 从shp文件中提取自然地块数据 add by duanwg
     *
     * @param shpFile shp文件地址
     * @param where   过滤条件
     * @return
     */
    public static List<java.util.Map<String, String>> getDataFromShp(String shpFile, String where) {
        List<java.util.Map<String, String>> listMaps = new ArrayList<java.util.Map<String, String>>();
        try {
            // 查询条件:类似数据库的查询条件
            // String str = "YFBHU='2757715'";

            // shp文件
            // ILayer layerDKShp = new
            // FeatureLayer(Environment.getExternalStorageDirectory().getAbsolutePath()
            // + "/FlightTarget/目标.shp");
            ILayer layerDKShp = new FeatureLayer(shpFile);
            // 获取Datatable数据表
            IFeatureClass featureClass = (IFeatureClass) ((IFeatureLayer) layerDKShp).getFeatureClass();
            ((ShapeFileClass) featureClass).getAllFeature();
            DataTable dt = featureClass.getAttributeTable();

            // 数据行集合
            DataRowCollection drc = dt.getRows();
            // 数据列集合
            DataColumnCollection dcc = dt.getColumns();
            // 数据下标
            List<Integer> list = dt.Select(where);
            // 循环赋值
            for (int i = 0; i < list.size(); i++) {
                java.util.Map<String, String> map = new HashMap<String, String>();
                for (int j = 0; j < dcc.size(); j++) {
                    map.put(dcc.get(j).getColumnName(),// 列名（key）
                            drc.get(list.get(i)).getStringCHS(dcc.get(j).getColumnName())// 字段值(value)
                    );
                }
                /* geo转换为wkt */
                byte[] bytes = null;
                bytes = srs.Geometry.FormatConvert.PolygonToWKB((IPolygon) featureClass.getGeometry(list.get(i)));
                if (null != bytes) {
                    String wkt = org.gdal.ogr.Geometry.CreateFromWkb(bytes).ExportToWkt();
                    map.put("GEO", wkt);
                }
                listMaps.add(map);
            }
        } catch (sRSException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return listMaps;
    }

}
